package top.starmc.starpet.util

import taboolib.common.util.replaceWithOrder
import javax.script.ScriptEngineManager

private val JAVA_SCRIPT = ScriptEngineManager().getEngineByName("JavaScript")

fun String.calculate(): Number {
    return try {
        JAVA_SCRIPT.eval(this) as Number
    } catch (ignored: Exception) {
        -1
    }
}

fun String.calculate(vararg args: Any): String {
    return run {
        var result = replaceWithOrder(*args)
        extract("<:", ":>").forEach {
            result = result.replace("<:$it:>", it.calculate().toString())
        }
        result
    }
}

fun String.extract(prefix: String, suffix: String): List<String> {
    return mutableListOf<String>().apply {
        val args = split(prefix)
        for (i in 1 until args.size) {
            this += args[i].split(suffix)[0]
        }
    }
}